package com.spring.lo.framework.factory.support;

import com.spring.lo.framework.factory.BeanFactory;
import com.spring.lo.framework.factory.config.PropertyValue;
import com.spring.lo.framework.factory.config.RuntimeBeanReference;
import com.spring.lo.framework.factory.config.TypedStringValue;

/**
 * BeanDefinition值解析器
 * @author zhangbh
 * 2023-05-28 22:53
 **/
public class BeanDefinitionValueResolver {

    private BeanFactory beanFactory;

    public BeanDefinitionValueResolver(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    /**
     * 转换BeanDefinition中的属性值为实际类型
     * @param value 值{@link PropertyValue#getValue()}
     * @return 实际类型值
     */
    public Object parseValue(Object value) {
        Object valueToUse = null;
        // 判断值类型
        if (value instanceof TypedStringValue) {
            TypedStringValue ts = (TypedStringValue) value;
            valueToUse = handleType(ts);
        } else if (value instanceof RuntimeBeanReference) {
            // todo 这边会有循环依赖的隐患
            String ref = ((RuntimeBeanReference) value).getRef();
            valueToUse = beanFactory.getBean(ref);
        }
        return valueToUse;
    }

    /**
     * 解实际类型
     * @param ts 带实际类型的字符串值
     * @return 实际类型
     */
    private Object handleType(TypedStringValue ts) {
        Class<?> targetType = ts.getTargetType();
        String stringValue = ts.getValue();
        Object result = null;
        // 基础类型转换
        if (targetType == String.class) {
            result = stringValue;
        } else if (targetType == Integer.class) {
            result = Integer.parseInt(stringValue);
        } else if (targetType == Double.class) {
            result = Double.valueOf(stringValue);
        }
        // todo 这边还有很多类型，一样的判断，就不写了
        return result;
    }

}
